<script lang="ts" setup>
import {onMounted, ref, watchEffect} from 'vue'

import type {PageAdminMember, PageResp, AdminMemberInfo, BuyMember} from "@/type/member.ts";
import {adminBuyMember, buyMember, getPageAdminMembers} from "@/api/member";
import {ElMessage, ElMessageBox} from "element-plus";
import type {AddConsumption} from "@/type/consumption.ts";
import {addAConsumption, adminAddAConsumption} from "@/api/consumption";

// 查询-下拉框+输入框数据
const input = ref('')
const select = ref('1')

// 表格数据
const parentBorder = ref(false)
const tableData = ref<AdminMemberInfo[]>([]);

// 分页-当前页码+一页多少条数据+总数据量
const currentPage = ref(1)
const pageSize = ref(6)
const total = ref(20)

// 分页查询用户
const getPageAdminMember = async () => {
  const pageInfo: PageAdminMember = {
    memberId: select.value == '1' ? Number(input.value) : null,
    username: select.value == '2' ? input.value : '',
    memberName: select.value == '3' ? input.value : '',
    memberType: '会员',
    page: currentPage.value,
    pageSize: pageSize.value
  }
  console.log(pageInfo)
  const result = await getPageAdminMembers(pageInfo)
  if (result.code == 1) {
    total.value = result.data.total
    tableData.value = result.data.records
  }
}

// 续费会员
const buyMemberInfo = ref<BuyMember>({
  memberId: -1,
  membershipStartDate: null,
  membershipEndDate: null,
  days: 30
})
const DialogVisible = ref(false)
const radioValue = ref('30')
const editAdminMember = (memberInfo: any) => {
  if (buyMemberInfo.value) {
    buyMemberInfo.value.memberId = memberInfo.memberId
    buyMemberInfo.value.membershipStartDate = memberInfo.membershipStartDate
    buyMemberInfo.value.membershipEndDate = memberInfo.membershipEndDate
  }
  radioValue.value = '30'
  DialogVisible.value = true
}
const confirm = () => {
  ElMessageBox.confirm(
      '确定要购买此套餐?',
      '再次确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      }
  )
      .then(async () => {
        try {
          const consumption: AddConsumption = {
            memberId: buyMemberInfo.value.memberId,
            consumptionType: '会员',
            amount: Number(radioValue.value),
            relatedId: -1
          }
          const updateInfo: BuyMember = {
            memberId: buyMemberInfo.value.memberId,
            membershipStartDate: buyMemberInfo.value.membershipStartDate || null,
            membershipEndDate: buyMemberInfo.value.membershipEndDate || null,
            days: Number(radioValue.value),
          }
          const consumptionResult = await adminAddAConsumption(consumption)
          const updateResult = await adminBuyMember(updateInfo)
          if (consumptionResult.code === 1 && updateResult.code === 1) {
            ElMessage({
              type: 'success',
              message: '购买成功',
            });
            await getPageAdminMember() // 刷新列表
            DialogVisible.value = false
          } else {
            // 处理错误情况
            ElMessage({
              type: 'error',
              message: consumptionResult.message || updateResult.message || '购买失败，请稍后重试。',
            });
          }
        } catch (error) {
          // 捕获网络请求或其他异常
          ElMessage({
            type: 'error',
            message: '购买失败，请检查网络或稍后重试。',
          });
        }
      })
      .catch(() => {
        // 用户取消删除操作
        ElMessage({
          type: 'info',
          message: '购买取消',
        });
      });
}
// 挂载时查询一次
onMounted(() => {
  console.log(currentPage.value, pageSize.value)
  getPageAdminMember()
})

// 监控查询变量-有变则重新查询
watchEffect(() => {
  getPageAdminMember()
})
</script>


<template>
  <div class="course-container">
    <!--主要操作展示区-->
    <el-card>
      <div class="header-add-and-find">
        <!--左侧新增按钮-->
        <!--el-button type="primary" @click="addUser">新增用户</el-button>-->
        <!--右侧查询按钮-->
        <!--表示输入框的值绑定到 input 变量上，实现双向数据绑定-->
        <el-input
            v-model="input"
            class="input-with-select"
            clearable
            placeholder="（实时搜索）请输入"
            prefix-icon="Search"
            style="max-width: 600px"
        >
          <!--          下拉框-->
          <!--          v-model="select" 表示选择框的值绑定到 select 变量上，实现双向数据绑定-->
          <template #prepend>
            <el-select v-model="select" placeholder="Select" style="width: 115px">
              <el-option label="用户id" value="1"/>
              <el-option label="用户名" value="2"/>
              <el-option label="姓名" value="3"/>
            </el-select>
          </template>
        </el-input>
      </div>


      <div class="info-main">
        <el-table :border="parentBorder" :data="tableData" max-height="445" style="width: 100%" table-layout="fixed">
          <!--详细数据展开-->
          <el-table-column type="expand">
            <template #default="props">
              <div class="detail-info" style="display: flex; justify-content: center">
                <el-card
                    style="margin: 20px; width: 75%; border-radius: 12px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);">
                  <div style="display: flex;">
                    <!-- 左侧：头像 -->
                    <div
                        style="flex: 0 0 150px; display: flex; justify-content: center; align-items: center; padding: 20px;">
                      <el-avatar :size="120" :src="props.row.avatar" style="border: 2px solid #eee;"></el-avatar>
                    </div>
                    <!-- 右侧：详细信息 -->
                    <div style="flex: 1; padding: 20px;">
                      <h2 style="margin: 0 0 10px; font-size: 24px; color: #333;">{{ props.row.username }}</h2>

                      <div style="display: flex; flex-wrap: wrap; gap: 10px;">
                        <p style="margin: 0; font-size: 16px; color: #666;"><strong>ID:</strong> {{
                            props.row.memberId
                          }}
                        </p>
                        <p style="margin: 0; font-size: 16px; color: #666;"><strong>性别:</strong> {{
                            props.row.gender
                          }}</p>
                        <p style="margin: 0; font-size: 16px; color: #666;"><strong>身高:</strong> {{
                            props.row.height
                          }}</p>
                        <p style="margin: 0; font-size: 16px; color: #666;"><strong>体重:</strong> {{
                            props.row.weight
                          }}</p>
                        <p style="margin: 0; font-size: 16px; color: #666;"><strong>BMI:</strong> {{
                            props.row.BMI
                          }}</p>
                        <p style="margin: 0; font-size: 16px; color: #666;"><strong>联系方式:</strong> {{
                            props.row.contact
                          }}</p>
                        <p style="margin: 0; font-size: 16px; color: #666;"><strong>注册时间:</strong> {{
                            props.row.registrationTime
                          }}</p>
                        <p style="margin: 0; font-size: 16px; color: #666;"><strong>修改时间:</strong> {{
                            props.row.lastModifiedTime
                          }}</p>
                        <p style="margin: 0; font-size: 16px; color: #666;"><strong>年龄:</strong> {{
                            props.row.age
                          }}</p>
                        <p style="margin: 0; font-size: 16px; color: #666;"><strong>姓名:</strong> {{
                            props.row.memberName
                          }}</p>
                      </div>
                    </div>
                  </div>
                </el-card>
              </div>
            </template>
          </el-table-column>

          <!--表格展示-->
          <el-table-column align="center" label="ID" prop="memberId" width="100px"/>
          <el-table-column align="center" label="头像" width="150px">
            <template #default="props">
              <el-avatar :src="props.row.avatar"/>
            </template>
          </el-table-column>
          <el-table-column align="center" label="用户名" prop="username" width="150px"/>
          <el-table-column align="center" label="性别" prop="gender" width="150px"/>
          <el-table-column align="center" label="联系方式" prop="contact" width="150px"/>
          <el-table-column align="center" label="年龄" prop="age" width="150px"/>
          <el-table-column align="center" label="操作">
            <template #default="props">
              <el-button color="#E6A23C" icon="Edit" type="primary" @click="editAdminMember(props.row)">续费会员
              </el-button>
            </template>
          </el-table-column>
        </el-table>


        <!--分页-->
        <div class="pagination-block">
          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :background="true"
              :page-sizes="[6, 8, 10, 12, 14]"
              :total="total"
              layout="prev, pager, next, jumper, ->,sizes, total"
          />
        </div>
      </div>
      <!-- 购买会员Dialog -->
      <div class="open-membership-dialog">
        <el-dialog
            v-model="DialogVisible"
            :show-close="false"
            align-center
            title="开通（续费）会员"
            width="500px"
            class="membership"
        >
          <p style="margin: 10px">请选择套餐</p>
          <el-radio-group v-model="radioValue" size="large">
            <el-radio-button label="30￥/月" value="30"/>
            <el-radio-button label="90￥/3月" value="90"/>
            <el-radio-button label="180￥/6月" value="180"/>
            <el-radio-button label="360￥/年" value="360"/>
          </el-radio-group>
          <template #footer>
            <el-button type="primary" @click="confirm">确认</el-button>
          </template>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>

</style>